package upload

import (
	"GraduationProject/public/tools"
	"GraduationProject/webserver/controllers/util"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"time"
)

// todo: 上传图片有问题 seek = 0
func Image(ctx *gin.Context) {
	img, err := ctx.FormFile("avatar")
	if err != nil {
		util.FailedResponse(ctx, 10001, "未上传文件")
		return
	}
	file, err := img.Open()
	if err != nil {
		util.FailedResponse(ctx, 10002, "文件未知错误")
		return
	}
	defer file.Close()

	md5Obj := md5.New()
	if _, err := io.Copy(md5Obj, file); err != nil {
		util.FailedResponse(ctx, 10003, "生成文件名失败")
		return
	}
	md5Obj.Write([]byte(time.Now().String()))
	filename := hex.EncodeToString(md5Obj.Sum(nil))

	i, err := file.Seek(0, 0)
	if err != nil {
		util.FailedResponse(ctx, 10004, "文件未知错误")
		return
	}

	fmt.Println("file.Seek:", i)
	newFile, err := os.Create("static/image/" + filename)
	if err != nil {
		util.FailedResponse(ctx, 10005, "文件存储出错")
		return
	}
	defer newFile.Close()

	if _, err := io.Copy(newFile, file); err != nil {
		util.FailedResponse(ctx, 10006, "文件存储出错")
		return
	}

	util.SuccessResponse(ctx, "url", tools.Conf.Get("host")+"/static/image/"+filename)
}
